<template>
  <div id="appManagePage">
    <!-- 搜索区域 -->
    <a-card class="search-card" :bordered="false">
      <template #title>
        <SearchOutlined class="card-icon" />
        搜索筛选
      </template>
      <a-form :model="searchParams" layout="inline" @finish="doSearch" class="search-form">
        <a-form-item label="应用名称">
          <a-input
            v-model:value="searchParams.appName"
            placeholder="请输入应用名称"
            allow-clear
            class="search-input"
          >
            <template #prefix>
              <AppstoreOutlined class="input-icon" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="创建者">
          <a-input
            v-model:value="searchParams.userId"
            placeholder="请输入用户ID"
            allow-clear
            class="search-input"
          >
            <template #prefix>
              <UserOutlined class="input-icon" />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="生成类型">
          <a-select
            v-model:value="searchParams.codeGenType"
            placeholder="请选择生成类型"
            allow-clear
            class="search-select"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option
              v-for="option in CODE_GEN_TYPE_OPTIONS"
              :key="option.value"
              :value="option.value"
            >
              {{ option.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button html-type="submit" type="primary" class="search-btn">
              <SearchOutlined />
              搜索
            </a-button>
            <a-button @click="resetSearch" class="reset-btn">
              <ReloadOutlined />
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 数据表格 -->
    <a-card class="table-card" :bordered="false">
      <template #title>
        <TableOutlined class="card-icon" />
        应用列表
      </template>
      <template #extra>
        <a-space>
          <a-button type="primary" @click="addApp" class="add-btn">
            <PlusOutlined />
            新增应用
          </a-button>
          <a-button @click="fetchData" class="refresh-btn">
            <ReloadOutlined />
            刷新
          </a-button>
        </a-space>
      </template>

      <a-table
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        :loading="loading"
        @change="doTableChange"
        class="app-table"
        :scroll="{ x: 1200 }"
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'cover'">
            <ImagePreview
              v-if="record.cover"
              :image-url="record.cover"
              :alt="`${record.appName} 的封面`"
              :title="`${record.appName} 的封面`"
            >
              <a-image :height="40" :src="record.cover" :width="60" class="app-cover" />
            </ImagePreview>

            <div v-else class="no-cover">
              <PictureOutlined />
              无封面
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'appName'">
            <div class="app-name">
              <a-tooltip :title="record.appName" placement="topLeft">
                <strong>{{ record.appName }}</strong>
              </a-tooltip>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'initPrompt'">
            <a-tooltip :title="record.initPrompt" placement="topLeft">
              <div class="prompt-text">{{ record.initPrompt || '暂无提示词' }}</div>
            </a-tooltip>
          </template>
          <template v-else-if="column.dataIndex === 'codeGenType'">
            <a-tag color="blue">
              {{ formatCodeGenType(record.codeGenType) }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'priority'">
            <a-tag v-if="record.priority === 99" color="gold">
              <StarOutlined />
              精选
            </a-tag>
            <span v-else class="priority-text">
              <a-tag color="green">{{ record.priority || '默认' }}</a-tag>
            </span>
          </template>
          <template v-else-if="column.dataIndex === 'deployedTime'">
            <span v-if="record.deployedTime" class="time-text">
              <a-tag color="green">已部署</a-tag>
            </span>
            <a-tag v-else color="orange">未部署</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'createTime'">
            <span class="time-text">
              {{ formatTime(record.createTime) }}
            </span>
          </template>
          <template v-else-if="column.dataIndex === 'user'">
            <UserInfo :user="record.user" size="small" />
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="primary" size="small" @click="editApp(record)" class="edit-btn">
                <EditOutlined />
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这个应用吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="delApp(record.id)"
              >
                <a-button danger size="small" class="delete-btn">
                  <DeleteOutlined />
                  删除
                </a-button>
              </a-popconfirm>
              <a-dropdown>
                <a-button size="small" class="more-btn" title="更多操作">
                  <EllipsisOutlined style="font-size: 14px" />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item
                      :key="record.priority === 99 ? 'unfeature' : 'feature'"
                      @click="toggleFeatured(record)"
                    >
                      <StarOutlined v-if="record.priority !== 99" />
                      <StarFilled v-else />
                      {{ record.priority === 99 ? '取消精选' : '设为精选' }}
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { deleteApp, listAppVoByPageAdmin, updateApp } from '@/api/appController'
import { CODE_GEN_TYPE_OPTIONS, formatCodeGenType } from '@/utils/codeGenType.ts'
import { formatTime } from '@/utils/time'
import UserInfo from '@/components/UserInfo.vue'
import ImagePreview from '@/components/ImagePreview.vue'
import {
  SearchOutlined,
  UserOutlined,
  AppstoreOutlined,
  TableOutlined,
  PlusOutlined,
  ReloadOutlined,
  EditOutlined,
  DeleteOutlined,
  PictureOutlined,
  StarOutlined,
  StarFilled,
  EllipsisOutlined,
} from '@ant-design/icons-vue'

const router = useRouter()

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 160,
    align: 'center',
  },
  {
    title: '应用名称',
    dataIndex: 'appName',
    align: 'center',
  },
  {
    title: '封面',
    dataIndex: 'cover',
    align: 'center',
  },
  {
    title: '生成类型',
    dataIndex: 'codeGenType',
    align: 'center',
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    align: 'center',
  },
  {
    title: '部署时间',
    dataIndex: 'deployedTime',
    align: 'center',
  },
  {
    title: '创建者',
    dataIndex: 'user',
    width: 120,
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 160,
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 230,
    align: 'center',
  },
]

// 数据
const data = ref<API.AppVO[]>([])
const total = ref(0)
const loading = ref(false)

// 搜索条件
const searchParams = reactive<API.AppQueryRequest>({
  pageNum: 1,
  pageSize: 10,
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await listAppVoByPageAdmin({
      ...searchParams,
    })
    if (res.data.data) {
      data.value = res.data.data.records ?? []
      total.value = res.data.data.totalRow ?? 0
    } else {
      message.error('获取数据失败，' + res.data.message)
    }
  } catch (error) {
    console.error('获取数据失败：', error)
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时请求一次
onMounted(() => {
  fetchData()
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.pageNum ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total: number) => `共 ${total} 条`,
  }
})

// 表格变化处理
const doTableChange = (page: { current: number; pageSize: number }) => {
  searchParams.pageNum = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 搜索
const doSearch = () => {
  // 重置页码
  searchParams.pageNum = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchParams, {
    pageNum: 1,
    pageSize: 10,
    appName: undefined,
    userId: undefined,
    codeGenType: undefined,
  })
  fetchData()
}

// 新增应用
const addApp = () => {
  router.push('/app/edit')
}

// 编辑应用
const editApp = (app: API.AppVO) => {
  router.push(`/app/edit/${app.id}`)
}

// 切换精选状态
const toggleFeatured = async (app: API.AppVO) => {
  if (!app.id) return

  const newPriority = app.priority === 99 ? 0 : 99

  try {
    const res = await updateApp({
      id: app.id,
      priority: newPriority,
    })

    if (res.data.code === 0) {
      message.success(newPriority === 99 ? '已设为精选' : '已取消精选')
      // 刷新数据
      fetchData()
    } else {
      message.error('操作失败：' + res.data.message)
    }
  } catch (error) {
    console.error('操作失败：', error)
    message.error('操作失败')
  }
}

// 删除应用
const delApp = async (id: number | undefined) => {
  if (!id) return

  try {
    const res = await deleteApp({ id })
    if (res.data.code === 0) {
      message.success('删除成功')
      // 刷新数据
      await fetchData()
    } else {
      message.error('删除失败：' + res.data.message)
    }
  } catch (error) {
    console.error('删除失败：', error)
    message.error('删除失败')
  }
}
</script>

<style scoped>
#appManagePage {
  margin: 0 auto;
  padding: 16px 24px;
}

/* 卡片样式 */
.search-card,
.table-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.search-card .ant-card-head,
.table-card .ant-card-head {
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.card-icon {
  margin-right: 8px;
  color: #6c5ce7;
}

/* 搜索表单 */
.search-form {
  padding: 8px 0;
}

.search-input,
.search-select {
  width: 200px;
}

.input-icon {
  color: #bfbfbf;
}

.search-btn {
  background: linear-gradient(135deg, #6c5ce7, #5a4fcf);
  border: none;
  box-shadow: 0 2px 8px rgba(108, 92, 231, 0.3);
}

.reset-btn {
  border-color: #d9d9d9;
}

.reset-btn:hover {
  border-color: #6c5ce7;
  color: #6c5ce7;
}

/* 表格样式 */
.app-table {
  background: white;
}

.app-table .ant-table-thead > tr > th {
  background: #fafafa;
  font-weight: 600;
  color: #262626;
  border-bottom: 2px solid #e8e8e8;
  padding: 8px 16px;
  text-align: center;
}

.app-table .ant-table-tbody > tr > td {
  padding: 8px 16px;
  vertical-align: middle;
  text-align: center;
}

.app-table .ant-table-tbody > tr:hover > td {
  background: rgba(108, 92, 231, 0.04);
}

/* 应用数据样式 */
.app-cover {
  border-radius: 8px;
  border: 2px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.app-cover:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.no-cover {
  width: 60px;
  height: 40px;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
  border-radius: 8px;
  border: 2px solid #e8e8e8;
  margin: 0 auto;
}

.no-cover .anticon {
  font-size: 16px;
  margin-bottom: 4px;
}

.app-name {
  color: #262626;
  font-size: 14px;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.prompt-text {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #666;
}

.time-text {
  color: #666;
  font-size: 13px;
}

.priority-text {
  color: #666;
  font-weight: 500;
}

/* 操作按钮 */
.edit-btn {
  background: linear-gradient(135deg, #6c5ce7, #5a4fcf);
  border: none;
  box-shadow: 0 2px 6px rgba(108, 92, 231, 0.3);
}

.edit-btn:hover {
  background: linear-gradient(135deg, #7c6ce8, #6c5ce7);
  transform: translateY(-1px);
}

.more-btn {
  border: 1px solid #e8e8e8;
  color: #666;
  background: #fafafa;
  border-radius: 6px;
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  width: 32px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}

.more-btn:hover {
  border-color: #6c5ce7;
  color: #6c5ce7;
  background: rgba(108, 92, 231, 0.08);
  box-shadow: 0 2px 6px rgba(108, 92, 231, 0.2);
  transform: translateY(-1px);
}

.more-btn:active {
  transform: translateY(0);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.delete-btn {
  box-shadow: 0 2px 6px rgba(255, 77, 79, 0.3);
}

.delete-btn:hover {
  transform: translateY(-1px);
}

/* 新增按钮 */
.add-btn {
  background: linear-gradient(135deg, #6c5ce7, #5a4fcf);
  border: none;
  box-shadow: 0 2px 6px rgba(108, 92, 231, 0.3);
}

.add-btn:hover {
  background: linear-gradient(135deg, #7c6ce8, #6c5ce7);
  transform: translateY(-1px);
}

/* 刷新按钮 */
.refresh-btn {
  border-color: #6c5ce7;
  color: #6c5ce7;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  background: rgba(108, 92, 231, 0.06);
  border-color: #6c5ce7;
  color: #6c5ce7;
  transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  #appManagePage {
    max-width: 100%;
    padding: 16px 20px;
  }
}

@media (max-width: 768px) {
  #appManagePage {
    padding: 12px 16px;
  }

  .search-input,
  .search-select {
    width: 160px;
  }

  .search-form .ant-form-item {
    margin-bottom: 16px;
  }

  .search-card,
  .table-card {
    margin-bottom: 16px;
  }
}

@media (max-width: 480px) {
  #appManagePage {
    padding: 8px 12px;
  }

  .search-input,
  .search-select {
    width: 140px;
  }
}

/* 紫色主题色定义 */
:root {
  --primary-color: #6c5ce7;
  --primary-hover: #7c6ce8;
  --primary-dark: #5a4fcf;
  --primary-light: rgba(108, 92, 231, 0.06);
}

/* 动画效果 */
.search-btn,
.reset-btn,
.edit-btn,
.delete-btn,
.add-btn,
.refresh-btn,
.more-btn {
  transition: all 0.3s ease;
}

.app-table .ant-table-tbody > tr {
  transition: background-color 0.3s ease;
}

.search-card,
.table-card {
  transition: box-shadow 0.3s ease;
}

.search-card:hover,
.table-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}
</style>
